var initShareBtn = function () {
  if ($('.bdsharebuttonbox').length > 0) {
    window._bd_share_main = null;
    $('head')
    .find('script[src*="http://bdimg.share.baidu.com/static/api/js/share.js"]').remove()
    .end()
    .find('link[href*="http://bdimg.share.baidu.com/static/api/css/"]').remove();

    window._bd_share_config = {
      common: {
        bdSnsKey: {},
        bdTexta: '',
        bdMini: '2',
        bdMiniList: false,
        bdPic: '',
        bdStyle: '1',
        bdSize: '32'
      },
      share: {}
    };

    var script = '<script src="http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + +~(-new Date() / 36e5) + '"></script>';
    $('head').append(script);
  }
};

var initMap = function () {
    if ($('.googlemapcontent').length > 0) {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 13,
        center: {lat: 25.001689, lng: 121.460809}
        });
        var geocoder = new google.maps.Geocoder();

        geocodeAddress(geocoder, map);
    };

    if ($('.baidumapcontent').length > 0) {
      // 百度地图API功能
      var address = $('#address').val();
      var map = new BMap.Map("map");
      var point = new BMap.Point(116.331398,39.897445);
      map.centerAndZoom(point,12);
      // 创建地址解析器实例
      var myGeo = new BMap.Geocoder();
      // 将地址解析结果显示在地图上,并调整地图视野
      myGeo.getPoint(address, function(point){
          if (point) {
              map.centerAndZoom(point, 16);
              map.addOverlay(new BMap.Marker(point));
          }else{
              alert("您选择地址没有解析到结果!");
          }
      }, "中国");
    }
};

var initEmbedDiv = function () {
    $('.text-read iframe').each(function (index, iframe) {
      if (iframe.src.indexOf('streetvoice') == -1) {    // 排除 SV Embed
        $(this).wrap('<div class="embed-responsive embed-responsive-4by3" />');
      }
    });
};

var infScroll = null;
var initScroll = function () {
    if (infScroll){
      infScroll.destroy();
      infScroll = null;
    }
    if ($('.cbp-so-scroller').length > 0) {
      infScroll = new InfiniteScroll('.cbp-so-scroller', {
          path: window.location.pathname + '?DAY{{#}}',
          append: '.cbp-so-section',
      });
    }
}

function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('address').value;
    geocoder.geocode({'address': address}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
        resultsMap.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: resultsMap,
            position: results[0].geometry.location
          });
    } else {
        alert('Geocode was not successful for the following reason: ' + status);
    }
    });
}

function init_city() {
    $('.change_city').on('click', function() {
      var url = $(this).attr('data-href');
      $('#modal-city').one('hidden.bs.modal', function(){
        $.pjax({
          url: url,
          container: '#pjax-container',
        });
      });
      $('#modal-city').modal('hide');
    });
}

function wechat_sign() {
    var current_url=location.href.split('#')[0];
    $.ajax({
      url: '/wechat_sign/',
      type: 'POST',
      encoding: 'UTF-8',
      dataType: 'json',
      data: { url: current_url },
      cache: false,
      success: function (resp) {
          if (resp.success === true){
            wx.config({
                debug: false,
                appId: resp.app_id,
                timestamp: resp.timestamp,
                nonceStr: resp.nonce_str,
                signature: resp.signature,
                jsApiList: [
                        'onMenuShareAppMessage',
                        'onMenuShareTimeline',
                    ],
            });
            wx.ready(function(){
                wx.onMenuShareTimeline({
                    title: $('title').text(), // 分享标题
                    link: current_url, // 分享链接
                    imgUrl: $('#weixin_cover').find('img').attr('src'), // 分享图标
                    success: function () {
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调函数
                    }
                });
                wx.onMenuShareAppMessage({
                    title: $('title').text(), // 分享标题
                    desc: '', // 分享描述
                    link: current_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: $('#weixin_cover').find('img').attr('src'), // 分享图标
                    success: function () {
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调函数
                    }
                });
            });
          }else{
            // TW站暂时不处理
          }
        }
    });
}

$(function(){
    var $nav = $('#bs-example-navbar-collapse-1');

    var hideNav = function () {
      if ($nav.hasClass('in')) {
        $nav.collapse('hide');
      }
    };

    $.djangocsrf( "enable" );

    $(document).pjax('a:not(".no-pjax")', '#pjax-container', { timeout: 5000 });

    $(document).on('pjax:start', function() {
      $('#weixin_cover').find('img').attr('src', 'http://simplelife.streetvoice.cn/asset/images/logo-300x300.jpg');  // 每次切换页面清空 weixin_cover
    });

    $(document).on('submit', '#search_form', function(event) {
        event.preventDefault(); // stop default submit behavior
        $.pjax.submit(event, '#pjax-container');
    });

    $(document).on('click', '.icon-info-open', function(event) {
      event.preventDefault();
      $(this).css("display", "none");
      $(".icon-info-close").css("display", "block");
      $(".ripple-article-info").css("transform", "translateX(0)");
    });

    $(document).on('click', '.icon-info-close', function(event) {
      event.preventDefault();
      $(this).css("display", "none");
      $(".icon-info-open").css("display", "block");
      $(".ripple-article-info").css("transform", "translateX(-80%)");
    });

    $(document).on('pjax:popstate', function () {
      $('.iosSlider').iosSlider('destroy');
    });

    $(document).on('pjax:beforeReplace', function () {
      $('.iosSlider').iosSlider('destroy');
    });

    $(document).on('pjax:end', function() {
      randomBackground();
      initShareBtn();
      start_iosslider();
      initMap();
      initEmbedDiv();
      wechat_sign();
      init_city();
      initScroll();
    });

    $('body').on('click', hideNav);

    window.onscroll = hideNav;

    initShareBtn();
    start_iosslider();
    initMap();
    initEmbedDiv();
    wechat_sign();
    init_city();
    initScroll();
});
